package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.lowcode.LowCodeExecuteService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.lowcodeexecute.pojo.dto.LowCodeExecuteRequestDTO;
import com.xbongbong.pro.lowcodeexecute.pojo.vo.LowCodeExecuteRequestVO;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/03/17 15:15
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/lowCodeExecute")
public class LowCodeExecuteController {

    @Resource
    private LowCodeExecuteService lowCodeExecuteService;

    /**
     * request
     *
     * @param lowCodeExecuteRequestDTO
     */
    @RequestMapping(value = "/request", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String request(@RequestBody @Valid LowCodeExecuteRequestDTO lowCodeExecuteRequestDTO, BindingResult br) throws Exception {
        XbbResponse<LowCodeExecuteRequestVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                String result = lowCodeExecuteService.request(lowCodeExecuteRequestDTO);
                return result;
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
